<template>
  <BasicDrawer @register="registerBaseDrawer" :title="`${spaceName}---预约列表`" width="800" destroyOnClose>
    <BasicTable @register="registerTable" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-button type="primary" @click="handleCreate" v-if="!disableUserEdit"> 预约</a-button>
      </template>
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)" />
      </template>
    </BasicTable>
    <a-row>
      <a-range-picker
        v-if="isShowTime"
        :show-time="{ format: 'HH:mm' }"
        format="YYYY-MM-DD HH:mm"
        :placeholder="['开始时间', '结束时间']"
        @change="onRangeChange"
        @ok="onRangeOk"
      />
    </a-row>
    <!--用户操作抽屉-->
    <UserDrawer @register="registerDrawer" @success="handleSuccess" />
    <!--用户选择弹窗-->
    <UseSelectModal @register="registerModal" @select="selectOk" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, watch, unref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/src/components/Table';
  import { BasicDrawer, useDrawer, useDrawerInner } from '/src/components/Drawer';
  import { useModal } from '/src/components/Modal';
  import UserDrawer from './UserDrawer.vue';
  import UseSelectModal from './UseSelectModal.vue';
  import { reservationList, deleteUserRole, batchDeleteUserRole, addUserRole } from '../role.api';
  import { userColumns, searchUserFormSchema } from '../role.data';
  import { getUserRoles } from '/@/views/system/user/user.api';
  import { useUserStore } from '/@/store/modules/user';
  const { userInfo } = useUserStore();
  const emit = defineEmits(['register', 'hideUserList']);
  const props = defineProps({
    disableUserEdit: { type: Boolean, default: false },
  });
  const isShowTime = ref(false);
  const spaceName = ref('');
  const checkedKeys = ref<Array<string | number>>([]);
  const roleId = ref('');
  const [registerBaseDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    roleId.value = data.id;
    spaceName.value = data.spaceName;
    setProps({ searchInfo: { spaceId: data.id } });
    reload();
  });
  //注册drawer
  const [registerDrawer, { openDrawer }] = useDrawer();
  //注册drawer
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, updateTableDataRecord, setProps }] = useTable({
    api: reservationList,
    columns: userColumns,
    formConfig: {
      //update-begin---author:wangshuai ---date:20230703  for：【QQYUN-5685】3、租户角色下,查询居左显示
      labelWidth: 60,
      //update-end---author:wangshuai ---date:20230703  for：【QQYUN-5685】3、租户角色下,查询居左显示
      // schemas: searchUserFormSchema,
      // fieldMapToTime: [['sendTime', ['startTime', 'endTime'], 'YYYY-MM-DD']],
      autoSubmitOnEnter: true,
    },
    striped: true,
    useSearchForm: true,
    showTableSetting: true,
    clickToRowSelect: false,
    bordered: true,
    showIndexColumn: false,
    // 【issues/1064】列设置的 cacheKey
    tableSetting: { fullScreen: true, cacheKey: 'role_user_table' },
    canResize: false,
    rowKey: 'id',
    actionColumn: {
      width: 180,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    },
  });

  /**
   * 选择列配置
   */
  const rowSelection = {
    type: 'checkbox',
    columnWidth: 50,
    selectedRowKeys: checkedKeys,
    onChange: onSelectChange,
  };

  /**
   * 选择事件
   */
  function onSelectChange(selectedRowKeys: (string | number)[], selectionRows) {
    checkedKeys.value = selectedRowKeys;
  }

  function onRangeOk(dates) {
    if (dates && dates.length === 2) {
      const startTime = dates[0].format('YYYY-MM-DD HH:mm:ss'); // 格式化开始时间
      const endTime = dates[1].format('YYYY-MM-DD HH:mm:ss'); // 格式化结束时间
      console.log('开始时间111111111:', startTime);
      console.log('结束时间2222222222:', endTime);
    }
    isShowTime.value = false;
  }
  /**
   * 新增
   */
  function handleCreate() {
    // isShowTime.value = true;
    openDrawer(true, {
      isUpdate: false,
      spaceId: roleId.value,
      isRole: true,
    });
  }
  /**
   * 编辑
   */
  async function handleEdit(record: Recordable) {
    try {
      record.spaceId = roleId.value;
    } catch (e) {
      console.log(e);
    }
    openDrawer(true, {
      record,
      spaceId: roleId.value,
      isUpdate: true,
      isRole: true,
    });
  }

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteUserRole({ id: record.id }, reload);
  }

  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDeleteUserRole({ userIds: checkedKeys.value.join(','), roleId: roleId.value }, () => {
      // update-begin--author:liaozhiyang---date:20240701---for：【TV360X-1655】批量取消关联之后清空选中记录
      reload();
      checkedKeys.value = [];
      // update-end--author:liaozhiyang---date:20240701---for：【TV360X-1655】批量取消关联之后清空选中记录
    });
  }

  /**
   * 成功回调
   */
  function handleSuccess({ isUpdate, values }) {
    isUpdate ? updateTableDataRecord(values.id, values) : reload();
  }
  /**
   * 选择已有用户
   */
  function handleSelect() {
    openModal(true);
  }
  /**
   * 添加已有用户
   */
  async function selectOk(val) {
    await addUserRole({ roleId: roleId.value, userIdList: val }, reload);
  }
  /**
   * 操作栏
   */
  function getTableAction(record) {
    return [
      {
        label: '预约修改',
        onClick: handleEdit.bind(null, record),
        ifShow: () => (record.reserverId = userInfo.id ? true : false),
      },
      {
        label: '撤销',
        popConfirm: {
          title: '是否确认撤销',
          confirm: handleDelete.bind(null, record),
        },
        ifShow: () => (record.reserverId = userInfo.id ? true : false),
      },
    ];
  }
</script>

<style scoped>
  /*update-begin---author:wangshuai ---date:20230703  for：【QQYUN-5685】3、租户角色下,查询居左显示*/
  :deep(.ant-form-item-control-input-content) {
    text-align: left;
  }
  /* 修改弹框位置 */
  .ant-picker-dropdown {
    top: 100px !important; /* 调整 top 值 */
    left: 50px !important; /* 调整 left 值 */
  }
  /*update-end---author:wangshuai ---date:20230703  for：【QQYUN-5685】3、租户角色下,查询居左显示*/
</style>
